package com.mes_for_xxxxxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mes_for_xxxxxx.context.BaseContext;
import com.mes_for_xxxxxx.entity.Processflow;
import com.mes_for_xxxxxx.entity.common.PageInfo;
import com.mes_for_xxxxxx.entity.common.Result;
import com.mes_for_xxxxxx.entity.dto.ProcessflowDTO;
import com.mes_for_xxxxxx.entity.dto.ReceiveProcessflowDTO;
import com.mes_for_xxxxxx.entity.page.ProcessflowPage;
import com.mes_for_xxxxxx.service.IProcessflowService;
import com.mes_for_xxxxxx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 工艺流程表 前端控制器
 * </p>
 *
 * @author 179005
 * @since 2024-09-10
 */
@RestController
@Slf4j
@RequestMapping("/processflow")
public class ProcessflowController {
    @Autowired
    private IProcessflowService processflowService;

    /**
     * pageInfo.getInput1()==》routerNumber
     *
     * @return
     */
    @PostMapping("/page")
    public Result pageProcessflow(@RequestBody ProcessflowPage pageInfo) {
        int pageSize = pageInfo.getPageSize();
        int pageNum = pageInfo.getPageNum();
        Page<Processflow> page = new Page<>(pageNum, pageSize);
        String worker = pageInfo.getWorker();
        String routeNumber = pageInfo.getRouteNumber();
        Integer status = pageInfo.getStatus();
        QueryWrapper<Processflow> queryWrapper = new QueryWrapper<>();
        if (pageInfo.getNextRoomCode() != null) {
            queryWrapper.eq("next_room_code", pageInfo.getNextRoomCode());
        }
        if (worker != null)
            queryWrapper.eq("worker", worker);
        if (routeNumber != null)
            queryWrapper.eq("route_number", routeNumber);
        if (status != null) {
            if (status == -1) {//查询当前未接受单
                queryWrapper.eq("status", -1);
            } else if (status == 2) {//查询下家未接收单
                queryWrapper.eq("status", 2);
            } else if (status == 0) {
                queryWrapper.eq("status", 0);
            } else if (status == 1) {
                queryWrapper.eq("status", 1);
            } else if (status == 3) {
                queryWrapper.eq("status", 3);
            }
        }
        return Result.success(processflowService.page(page, queryWrapper));
    }

    /**
     * 根据订单号，将当前工序向后延期一小时
     *
     * @param orderId
     * @return
     */
    @GetMapping("/delay/{orderId}")
    public Result delayProcessflow(@PathVariable String orderId) {
        processflowService.delayProcessflow(orderId);
        return Result.success();
    }


    /**
     * 根据订单号，将当前正常订单推进至下一环节
     * 工序单推进
     *
     * @param orderId
     * @return
     */
    @GetMapping("/push/status/{orderId}")
    public Result pushStatusProcessflow(@PathVariable String orderId) {
        int i = processflowService.pushStatusProcessflow(orderId);
        if (i != 0)
            return Result.error("当前订单状态无需手动推进，请您按正常流程提交工序表");
        return Result.success();
    }


    /**
     * 手动提交工序表，需要填写下一工序，工序人；当前工序所需设备
     *
     * @param dto
     * @return
     */
    @PostMapping("/push")
    public Result pushProcessflow(@RequestBody ProcessflowDTO dto) {
        processflowService.pushProcessflow(dto);
        return Result.success();
    }

    /**
     * 添加工序单
     *
     * @param processflow
     * @return
     */
    @PostMapping("/add")
    public Result addProcessflow(@RequestBody Processflow processflow) {
        //需手动填写 routeNumber，thisFlow，materialNumber，productName，nextRoomCode，firstMaterial
        // equipment
        return Result.success(processflowService.add(processflow));
    }

    /**
     * 押平上报 传入工单Id，入方上报物料数即可
     *
     * @param orderId
     * @param firstMaterial
     * @return
     */
    @GetMapping("/test/{orderId}/{firstMaterial}")
    public Result testOrder(@PathVariable String orderId, @PathVariable Integer firstMaterial) {
        processflowService.testOrder(orderId, firstMaterial);
        return Result.success();
    }

    /**
     * 接收工序单
     * 要求传入orderId，routeNumber，secondMaterial，equipment，nextRoomCode
     * 上述要求参数只有equipment和secondMaterial（入方核对物料数）是填的，剩下的都是传入的
     *
     * @param dto
     * @return
     */
    @PostMapping("/receive")
    public Result receive(@RequestBody ReceiveProcessflowDTO dto) {
        String token = dto.getToken();
        log.info("jwt校验:{}", token);
        Claims claims = JwtUtil.parseJWT("ezLogin", token);
        Long userId = Long.valueOf(claims.get("employee_id").toString());
        log.info("当前用户id：{}", userId);
        BaseContext.setCurrentId(userId);
        processflowService.receive(dto);
        return Result.success();
    }

    /**
     * 查询可接受的工单，会返回一个类似于分页查询的列表，但是不带分页，最多返回五条。
     * 按工序流转查询页面 稍作修改修改显示概要信息即可
     *
     * @param id
     * @return
     */
    @PostMapping("/accept/{id}")
    public Result accept(@PathVariable Integer id) {
        return Result.success(processflowService.accept(id));
    }
}
